package org.chen.task;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.chen.client.HeyGenClient;
import org.chen.common.utils.SnowflakeIdGenerator;
import org.chen.domain.entity.VideoAvatar;
import org.chen.mapper.AvatarMapper;
import org.chen.response.AvatarResponse;
import org.chen.utils.AvatarServiceUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class AvatarSyncTask {
    @Autowired
    private HeyGenClient heyGenClient;
    
    @Autowired
    private AvatarMapper avatarMapper;

    @Autowired
    private AvatarServiceUtils avatarServiceUtils;

    private static final int BATCH_SIZE = 500; // 每批处理的数据量

    @Scheduled(cron = "0 0 2 * * *")
//    @Scheduled(fixedRateString = "60000")
    @Transactional
    public void syncAvatars() {
        log.info("Start syncing avatars...");
        try {
            // 1. 获取API数据
            AvatarResponse response = heyGenClient.getAvatars();
            if (response == null || response.getData() == null || 
                response.getData().getAvatars() == null) {
                log.error("Invalid avatar response");
                return;
            }

//            List<AvatarResponse.Avatar> avatars = avatarServiceUtils.getCombinedAvatars(response);
            List<AvatarResponse.Avatar> avatars = response.getData().getAvatars();

            // 2. 获取现有数据
            List<String> existingAvatarIds = avatarMapper.selectAllAvatarIds();
            
            // 3. 分类处理
            List<VideoAvatar> toInsert = new ArrayList<>();
            List<VideoAvatar> toUpdate = new ArrayList<>();
            
            for (AvatarResponse.Avatar avatar : avatars) {
                VideoAvatar videoAvatar = convertToEntity(avatar);
                if (existingAvatarIds.contains(avatar.getAvatar_id())) {
                    toUpdate.add(videoAvatar);
                } else {
                    toInsert.add(videoAvatar);
                }
            }

            // 4. 分批处理插入
            if (!toInsert.isEmpty()) {
                Lists.partition(toInsert, BATCH_SIZE).forEach(batch -> {
                    avatarMapper.batchInsert(batch);
                    log.info("Inserted {} avatars", batch.size());
                });
            }

            // 5. 分批处理更新
            if (!toUpdate.isEmpty()) {
                Lists.partition(toUpdate, BATCH_SIZE).forEach(batch -> {
                    avatarMapper.batchUpdate(batch);
                });
            }
            
            log.info("Avatar sync completed successfully");
        } catch (Exception e) {
            log.error("Avatar sync failed", e);
        }
    }

    private VideoAvatar convertToEntity(AvatarResponse.Avatar avatar) {
        VideoAvatar entity = new VideoAvatar();
        // 使用雪花算法生成ID
        entity.setId(SnowflakeIdGenerator.nextId());
        entity.setAvatarId(avatar.getAvatar_id());
        entity.setAvatarName(avatar.getAvatar_name());
        entity.setGender(avatar.getGender());
        entity.setPreviewImageUrl(avatar.getPreview_image_url());
        entity.setPreviewVideoUrl(avatar.getPreview_video_url());
        entity.setPremium(avatar.getPremium());
        entity.setIsPublic(true);
        return entity;
    }
}